<template>
  <a-layout class="tn-label-design-box">
    <a-layout-header>
      <h3 class="design-header-title" :title="(labelName as any)">{{ labelName }}</h3>
      <div>
        <a-space>
          <a-button @click="clearAll()">清空</a-button>
          <a-button @click="printPrview()">打印预览</a-button>
          |
          <a-button type="primary" @click="save()">保存</a-button>
          <a-button type="primary" @click="save('close')">保存并关闭</a-button>
        </a-space>
      </div>
    </a-layout-header>
    <a-layout>
      <a-layout-sider width="100">
        <SilderLeft @addElement="addElement" />
      </a-layout-sider>
      <a-layout-content>
        <CanvasBox
          ref="refCanvasBox"
          v-model:elementIndex="elementIndex"
          :canvas-form="CanvasForm"
          :elements="Elements"
          @syncElData="syncElData"
        />

        <div v-if="Pz" class="box-btn">
          <a-button shape="circle" :icon="h(PlusOutlined)" @click="Pz.zoomIn"></a-button>
          <a-button shape="circle" :icon="h(MinusOutlined)" @click="Pz.zoomOut"></a-button>
          <a-button shape="circle" :icon="h(ReloadOutlined)" @click="Pz.reset"></a-button>
        </div>
      </a-layout-content>
      <a-layout-sider width="400">
        <FormBox
          :canvas-form="CanvasForm"
          :el-form="Elements[elementIndex === null ? -1 : elementIndex]"
          :field-list="fieldList"
          @changeElData="changeElData"
        />
      </a-layout-sider>
    </a-layout>
  </a-layout>
  <PrintBox ref="refPrint"></PrintBox>
</template>

<script setup lang="ts">
import { canvasFormSource } from './form'
import { ptToPx, setNewelement } from './mm2px'
import SilderLeft from './SilderLeft.vue'
import FormBox from './Form/index.vue'
import CanvasBox from './CavnasBox.vue'
import { h, onMounted, nextTick, ref } from 'vue'
import { MinusOutlined, PlusOutlined, ReloadOutlined } from '@ant-design/icons-vue'
import Panzoom from '@panzoom/panzoom'
import { useRoute } from 'vue-router'
import { Modal } from 'ant-design-vue'
import PrintBox from './Print/index.vue'

const props = defineProps<{
  fieldList: any[]
  designData?: any
}>()
const emits = defineEmits(['save'])
const route = useRoute()
const labelName = route.query.labelName

const refCanvasBox = ref()
const refPrint = ref()
const CanvasForm = ref<any>(canvasFormSource())
const Elements = ref<any[]>([])
const elementIndex = ref(null)

const Pz = ref()
onMounted(() => {
  nextTick(() => {
    const myCanvas = document.getElementById('myCanvas')
    if (myCanvas) {
      Pz.value = Panzoom(myCanvas, {
        excludeClass: 'design-canvas',
        disableZoom: false
      })
    }
  })
})

// 清空所有组件
function clearAll() {
  Modal.confirm({
    title: '提示',
    content: '是否确认清空画布？',
    zIndex: 999999,
    centered: true,
    okText: '确认',
    cancelText: '取消',
    onOk: () => {
      Elements.value = []
      elementIndex.value = null
      refCanvasBox.value.setCheckNull()
    }
  })
}

// 表单发生变化后，修改元素样式
function changeElData() {
  if (elementIndex.value === null) {
    return
  }
  const { width, height, left, top } = Elements.value[elementIndex.value]
  const el = document.getElementById('el' + elementIndex.value)

  if (el) {
    el.style.width = ptToPx(width) + 'px'
    el.style.height = ptToPx(height) + 'px'
    el.style.transform = `translate(${ptToPx(left)}px,${ptToPx(top)}px)`
    nextTick(() => {
      refCanvasBox.value.upDateMoveable()
    })
  }
}

function addElement(data) {
  Elements.value.push(data)
}

// 同步元素的值
function syncElData(data) {
  if (elementIndex.value === null) {
    return
  }
  Elements.value[elementIndex.value] = Object.assign(Elements.value[elementIndex.value], data)
}

// 初始化对象
function initData() {
  if (!props.designData) {
    return
  }
  const designForm = JSON.parse(props.designData)
  console.log(designForm.canvas)
  if (designForm.canvas.childCanvas1) {
    // designForm.elements = JSON.parse(
    //   '[{"top": 0.978851963746223, "left": 14.356495468277938, "size": "1", "type": 0, "ratio": false, "width": 21.752265861027187, "active": false, "height": 5.438066465256796, "content": "文本内容", "timestamp": 1698029207574}]'
    // )
    designForm.elements = setNewelement(designForm.elements, props.fieldList)
  }
  delete designForm.canvas.childCanvas1
  delete designForm.canvas.childCanvas2
  CanvasForm.value = designForm.canvas
  Elements.value = designForm.elements
}
initData()

const busiType = {
  barCode: '条形码',
  qrCode: '二维码',
  word: '文本文字',
  business: '业务字段'
}

function setDesc() {
  let str = ''
  // 画布设置
  str += `【画布设置】\n宽：${CanvasForm.value.width}, 高：${CanvasForm.value.height} `
  if (CanvasForm.value.offsetX && CanvasForm.value.offsetY) {
    str += `左偏移：${CanvasForm.value.offsetY}, 上偏移：${CanvasForm.value.offsetX}`
  }
  // 元素设置
  for (let i = 0; i < Elements.value.length; i++) {
    const element = Elements.value[i]
    str += `\n【${i + 1}、元素-${busiType[element.type]}】`
    str += `\n X：${element.left}, Y：${element.top}, 宽：${element.width}, 高：${element.height}`
    if (element.type === 'word') {
      str += `\n文字内容：${element.content}`
    }
    if (element.type === 'business' || element.type === 'word') {
      str += `\n文字大小：${element.size}`
    }
    if (element.type === 'business') {
      str += `\n分隔符：${element.separator}`
      str += `\n业务字段：`
      str += (element.fields || []).map((item) => item.fieldName).join('、')
    }
  }
  return str
}

// 保存
function save(isClose?) {
  if (CanvasForm.value.childCanvas1) {
    delete CanvasForm.value.childCanvas1
    delete CanvasForm.value.childCanvas2
  }
  emits('save', {
    canvas: CanvasForm.value,
    elements: Elements.value,
    desc: setDesc(),
    callBack() {
      if (isClose) {
        window.close()
      }
    }
  })
}

// 打印预览
function printPrview() {
  refPrint.value.show(
    [
      {
        labelNumber: '12345678',
        isTest: true
      }
    ],
    JSON.stringify({ canvas: CanvasForm.value, elements: Elements.value })
  )
}
</script>

<style lang="less">
.tn-label-design-box {
  position: fixed;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  background: #f2f2f2;
  .design-header-title {
    width: 500px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
  // z-index: 100001;
  .ant-layout-header {
    border-bottom: 1px solid #ddd;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 24px;
    h3 {
      margin: 0;
    }
  }
  .ant-tabs-nav {
    padding: 0 12px;
  }
  .ant-tabs-tabpane {
    position: absolute;
    top: 46px;
    padding: 20px 12px 0 12px;
    bottom: 0;
    overflow: auto;
  }
  .box-btn {
    position: absolute;
    right: 10px;
    bottom: 20px;
    width: 40px;
    .ant-btn {
      display: block;
      margin-top: 12px;
    }
  }
  .ant-layout-sider {
    background: #fff;
  }
  .ant-layout-content {
    position: relative;
  }
  .moveable-el {
    position: absolute;
    &.qrCode.active ~ .moveable-control-box .moveable-resizable {
      display: none;
    }
    &.barCode.active ~ .moveable-control-box .moveable-resizable {
      display: none;
      &.moveable-n,
      &.moveable-s {
        display: block;
      }
    }
    &.active {
      background: rgba(255, 255, 255, 0.6);
      .label-del-element {
        display: block;
      }
    }
  }
  .design-canvas-box {
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    margin: auto;
    width: 300px;
    height: 150px;
    .design-canvas {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background: #fff;
      cursor: pointer;
    }
    .design-mask {
      position: absolute;
      left: -12px;
      top: -12px;
      right: -12px;
      bottom: -36px;
      background: #ddd;
      border-radius: 8px;
      .mask-tips {
        position: absolute;
        bottom: 7px;
        color: #aaa;
        width: 100%;
        text-align: center;
        font-size: 12px;
      }
    }
  }
}
</style>
